package cn.juque.jdfsystem.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.juque.common.constants.YesOrNoEnum;
import cn.juque.jdfsystem.entity.FileInfo;
import cn.juque.jdfsystem.enums.ConfigCodeEnum;
import cn.juque.jdfsystem.helper.FileInfoHelper;
import cn.juque.jdfsystem.threads.DownloadFileThreadPool;
import cn.juque.lucenecandy.core.base.QueryWrapperBuilder;
import cn.juque.lucenecandy.core.enums.MatchTypeEnum;
import cn.juque.lucenecandy.helper.IndexHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.BooleanClause;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>CheckFileExistsTask</li>
 * </ul>
 * @date 2023-01-18 09:05:59
 **/
@Slf4j
@Service("checkFileExistsTask")
public class CheckFileExistsTask extends AbstractTask {

    @Resource
    private IndexHelper indexHelper;

    @Resource
    private DownloadFileThreadPool downloadFileThreadPool;

    @Resource
    private FileInfoHelper fileInfoHelper;

    /**
     * 任务逻辑
     *
     * @param args 参数
     */
    @Override
    public void execute(String[] args) {
        log.info("开始盘点缺失文件");
        String value = super.configInfoCache.getValue(ConfigCodeEnum.CHECK_FILE_LIMIT_DAY.getCode());
        if (CharSequenceUtil.isEmpty(value)) {
            log.info("盘点缺失文件的最大时限缺失");
            return;
        }
        int day = Integer.parseInt(value);
        // 盘点前一天
        Date maxDate = DateUtil.offsetDay(new Date(), -1);
        Date minDate = DateUtil.offsetDay(maxDate, -day);
        Integer maxDateInt = Integer.parseInt(DateUtil.format(maxDate, DatePattern.PURE_DATE_PATTERN));
        Integer minDateInt = Integer.parseInt(DateUtil.format(minDate, DatePattern.PURE_DATE_PATTERN));
        QueryWrapperBuilder<FileInfo> queryWrapperBuilder = new QueryWrapperBuilder<>(FileInfo.class);
        queryWrapperBuilder.matchRange(FileInfo::getCreateDate, minDateInt, maxDateInt, BooleanClause.Occur.MUST);
        String workspaceId = super.configInfoCache.getValue(ConfigCodeEnum.WORKSPACE_ID.getCode());
        queryWrapperBuilder.matchStr(
                FileInfo::getWorkspaceId, workspaceId, MatchTypeEnum.TERM, BooleanClause.Occur.MUST);
        queryWrapperBuilder.matchInt(FileInfo::getValidFlag, YesOrNoEnum.YES.getCode(), BooleanClause.Occur.MUST);
        List<FileInfo> fileList = this.indexHelper.search(queryWrapperBuilder.build());
        if (CollUtil.isEmpty(fileList)) {
            log.info("盘点缺失文件：没发现文件缺失");
            return;
        }
        fileList = fileList.stream().filter(f -> !FileUtil.exist(this.fileInfoHelper.getFile(f))).collect(Collectors.toList());
        List<Boolean> flagList = fileList.stream().map(f -> this.downloadFileThreadPool.submit(null, f)).collect(Collectors.toList());
        long count = flagList.stream().filter(Boolean.FALSE::equals).count();
        log.info("检索到缺失文件数:{}, 同步失败文件数:{}", CollUtil.size(fileList), count);
    }

    /**
     * 设置随机休眠等待最大时长 单位：秒
     *
     * @return 秒
     */
    @Override
    protected Integer initSleepTimes() {
        return null;
    }

    @Override
    protected String getTaskName() {
        return "CheckFileExistsTask";
    }
}
